package com.crm.business.crm.controller;

import com.crm.business.crm.log.CrmContactsLog;
import com.crm.business.crm.service.CrmUploadExcelService;
import com.crm.business.crm.service.ICrmContactsService;
import com.crm.business.utils.AuthUtil;
import com.crm.common.crm.common.CrmModel;
import com.crm.common.crm.constant.CrmCodeEnum;
import com.crm.common.crm.constant.CrmEnum;
import com.crm.common.crm.constant.FieldEnum;
import com.crm.common.crm.entity.BO.*;
import com.crm.common.crm.entity.PO.CrmContacts;
import com.crm.common.crm.entity.VO.CrmDataCheckVO;
import com.crm.common.crm.entity.VO.CrmInfoNumVO;
import com.crm.common.crm.entity.VO.CrmModelFiledVO;
import com.crm.common.ka.core.common.*;
import com.crm.common.ka.core.common.log.BehaviorEnum;
import com.crm.common.ka.core.common.log.SysLog;
import com.crm.common.ka.core.common.log.SysLogHandler;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.common.ka.core.exception.CrmException;
import com.crm.common.ka.core.feign.crm.entity.SimpleCrmEntity;
import com.crm.business.servlet.ApplicationContextHolder;
import com.crm.common.ka.core.servlet.upload.FileEntity;
import com.crm.business.utils.UserUtil;
import com.crm.common.utils.spring.SpringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 联系人表 前端控制器
 * </p>
 *
 * @author zhangzhiwei
 * @since 2020-05-26
 */
@RestController
@RequestMapping("/crmContacts")
@Api(tags = "联系人模块接口")
@SysLog(subModel = SubModelType.CRM_CONTACTS, logClass = CrmContactsLog.class)
public class CrmContactsController {

    @Autowired
    private ICrmContactsService crmContactsService;

    @PostMapping("/queryById/{contactsId}")
    @ApiOperation("根据ID查询")
    public Result<CrmModel> queryById(@PathVariable("contactsId") @ApiParam(name = "id", value = "id") Integer contactsId) {
        Integer number = crmContactsService.lambdaQuery().eq(CrmContacts::getContactsId, contactsId).count();
        if (number == 0) {
            throw new CrmException(CrmCodeEnum.CRM_DATA_DELETED, "联系人");
        }
        CrmModel model = crmContactsService.queryById(contactsId);
        return R.ok(model);
    }

    @PostMapping("/deleteByIds")
    @ApiOperation("根据ID删除数据")
    @SysLogHandler(behavior = BehaviorEnum.DELETE)
    public Result deleteByIds(@ApiParam(name = "ids", value = "id列表") @RequestBody List<Integer> ids) {
        crmContactsService.deleteByIds(ids);
        return R.ok();
    }

    @PostMapping("/queryPageList")
    @ApiOperation("查询列表页数据")
    public Result<BasePage<Map<String, Object>>> queryPageList(@RequestBody CrmSearchBO search) {
        search.setPageType(1);
        search.setSearch(search.getSearch().trim());
        BasePage<Map<String, Object>> mapBasePage = crmContactsService.queryPageList(search);
        return R.ok(mapBasePage);
    }

    @PostMapping("/field")
    @ApiOperation("查询新增所需字段")
    public Result<List<CrmModelFiledVO>> queryField() {
        List<CrmModelFiledVO> crmModelFiledList = crmContactsService.queryField(null);
        crmModelFiledList.removeIf(field -> field.getFieldName().equals("serialNumber"));
        crmModelFiledList.removeIf(field -> field.getFieldName().equals("backStatus"));
        return R.ok(crmModelFiledList);
    }

    @PostMapping("/field/{id}")
    @ApiOperation("查询修改数据所需信息")
    public Result<List<CrmModelFiledVO>> queryField(@PathVariable("id") @ApiParam(name = "id", value = "id") Integer id) {
        List<CrmModelFiledVO> crmModelFiledList = crmContactsService.queryField(id);
        crmModelFiledList.removeIf(field -> field.getFieldName().equals("serialNumber"));
        crmModelFiledList.removeIf(field -> field.getFieldName().equals("backStatus"));
        return R.ok(crmModelFiledList);
    }

    @PostMapping("/queryBusiness")
    @ApiOperation("联系人下查询商机")
    public Result<BasePage<Map<String, Object>>> queryBusiness(@RequestBody CrmBusinessPageBO businessPageBO) {
        boolean auth = AuthUtil.isCrmAuth(CrmEnum.CONTACTS, businessPageBO.getContactsId());
        if (auth) {
            throw new CrmException(SystemCodeEnum.SYSTEM_NO_AUTH);
        }
        BasePage<Map<String, Object>> page = crmContactsService.queryBusiness(businessPageBO);
        return R.ok(page);
    }

    @PostMapping("/relateBusiness")
    @ApiOperation("联系人关联商机")
    public Result relateBusiness(@RequestBody CrmRelateBusinessBO relateBusinessBO) {
        crmContactsService.relateBusiness(relateBusinessBO);
        return R.ok();
    }

    @PostMapping("/unrelateBusiness")
    @ApiOperation("联系人解除关联商机")
    public Result unrelateBusiness(@RequestBody CrmRelateBusinessBO relateBusinessBO) {
        crmContactsService.unrelateBusiness(relateBusinessBO);
        return R.ok();
    }

    @PostMapping("/changeOwnerUser")
    @ApiOperation("修改负责人")
    @SysLogHandler(behavior = BehaviorEnum.CHANGE_OWNER)
    public Result changeOwnerUser(@RequestBody CrmChangeOwnerUserBO crmChangeOwnerUserBO) {
        crmContactsService.changeOwnerUser(crmChangeOwnerUserBO.getIds(), crmChangeOwnerUserBO.getOwnerUserId());
        return R.ok();
    }

    @PostMapping("/batchExportExcel")
    @ApiOperation("选中导出")
    @SysLogHandler(behavior = BehaviorEnum.EXCEL_EXPORT, object = "选中导出", detail = "导出联系人")
    public void batchExportExcel(@RequestBody @ApiParam(name = "ids", value = "id列表") List<Integer> ids, HttpServletResponse response) {
        CrmSearchBO search = new CrmSearchBO();
        search.setPageType(10000);
        search.setLabel(CrmEnum.CONTACTS.getType());
        CrmSearchBO.Search entity = new CrmSearchBO.Search();
        entity.setFormType(FieldEnum.TEXT.getFormType());
        entity.setSearchEnum(CrmSearchBO.FieldSearchEnum.ID);
        entity.setValues(ids.stream().map(Object::toString).collect(Collectors.toList()));
        search.getSearchList().add(entity);
        search.setPageType(10000);
        crmContactsService.exportExcel(response, search);
    }

    @PostMapping("/allExportExcel")
    @ApiOperation("全部导出")
    @SysLogHandler(behavior = BehaviorEnum.EXCEL_EXPORT, object = "全部导出", detail = "导出联系人")
    public void allExportExcel(@RequestBody CrmSearchBO search, HttpServletResponse response) {
        search.setPageType(10000);
        crmContactsService.exportExcel(response, search);
    }

    @PostMapping("/add")
    @ApiOperation("保存数据")
    @SysLogHandler(behavior = BehaviorEnum.SAVE, object = "#crmModel.entity[name]", detail = "'新增了联系人:' + #crmModel.entity[name]")
    public Result add(@RequestBody CrmContactsSaveBO crmModel) {
        //籍贯
        if (crmModel.getEntity().get("mapAddress") != null && crmModel.getEntity().get("mapAddress") != "") {
            String[] address = crmModel.getEntity().get("mapAddress").toString().split(",");
            if(address.length == 3){
                String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + address[2] + "\"}";
                crmModel.getEntity().put("address", addr);
            }else if(address.length == 2){
                String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + "\"}";
                crmModel.getEntity().put("address", addr);
            }else if(address.length == 1){
                String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + "\", \"area\":\"" + "\"}";
                crmModel.getEntity().put("address", addr);
            }
        }

        //当前就业城市
        if (crmModel.getEntity().get("mapCity") != null && crmModel.getEntity().get("mapCity") != "") {
            String[] address = crmModel.getEntity().get("mapCity").toString().split(",");
            if(address.length == 3){
                String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + address[2] + "\"}";
                crmModel.getEntity().put("currentCity", addr);
            }else if(address.length == 2){
                String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + "\"}";
                crmModel.getEntity().put("currentCity", addr);
            }else if(address.length == 1){
                String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + "\", \"area\":\"" + "\"}";
                crmModel.getEntity().put("currentCity", addr);
            }
        }

//        //期望就业城市
//        if (crmModel.getEntity().get("mapWifsuu") != null && crmModel.getEntity().get("mapWifsuu") != ""){
//            String[] mapWifsuu = crmModel.getEntity().get("mapWifsuu").toString().split(",");
//            CrmModelFiledVO modelFiledVO = new CrmModelFiledVO();
//            modelFiledVO.setFieldId(1102017);
//            modelFiledVO.setFieldName("fliedWifsuu");
//            if(mapWifsuu.length == 3){
//                String addr = "{\"province\":\"" + mapWifsuu[0] + "\", \"city\":\"" + mapWifsuu[1] + "\", \"area\":\"" + mapWifsuu[2] + "\"}";
//                modelFiledVO.setValue(addr);
//                crmModel.getField().add(modelFiledVO);
//            }else if(mapWifsuu.length == 2){
//                String addr = "{\"province\":\"" + mapWifsuu[0] + "\", \"city\":\"" + mapWifsuu[1] + "\", \"area\":\"" + "\"}";
//                modelFiledVO.setValue(addr);
//                crmModel.getField().add(modelFiledVO);
//            }else if(mapWifsuu.length == 1){
//                String addr = "{\"province\":\"" + mapWifsuu[0] + "\", \"city\":\"" + "\", \"area\":\"" + "\"}";
//                modelFiledVO.setValue(addr);
//                crmModel.getField().add(modelFiledVO);
//            }
//        }

        crmContactsService.addOrUpdate(crmModel, false);
        return R.ok();
    }

    @PostMapping("/information/{id}")
    @ApiOperation("查询详情页信息")
    public Result<List<CrmModelFiledVO>> information(@PathVariable("id") @ApiParam(name = "id", value = "id") Integer id) {
        List<CrmModelFiledVO> information = crmContactsService.information(id);
        return R.ok(information);
    }

    @PostMapping("/update")
    @ApiOperation("修改数据")
    @SysLogHandler(behavior = BehaviorEnum.UPDATE)
    public Result update(@RequestBody CrmContactsSaveBO crmModel) {
        if (crmModel.getEntity().get("mapAddress") != null && crmModel.getEntity().get("mapAddress") != "") {
            if(crmModel.getEntity().get("mapAddress") instanceof String){
                String[] address = crmModel.getEntity().get("mapAddress").toString().split(",");
                if(address.length == 3){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + address[2] + "\"}";
                    crmModel.getEntity().put("address", addr);
                }else if(address.length == 2){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + "\"}";
                    crmModel.getEntity().put("address", addr);
                }else if(address.length == 1){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + "\", \"area\":\"" + "\"}";
                    crmModel.getEntity().put("address", addr);
                }else{
                    crmModel.getEntity().put("address",address);
                }
            }else if (crmModel.getEntity().get("mapAddress") instanceof LinkedHashMap){
                String province = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapAddress")).get("province");
                String city = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapAddress")).get("city");
                String area = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapAddress")).get("area");
                String addr = "{\"province\":\"" + province + "\", \"city\":\"" + city + "\", \"area\":\"" + area + "\"}";
                crmModel.getEntity().put("address", addr);
            }
            /*String[] address = crmModel.getEntity().get("mapAddress").toString().split(",");
            String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + address[2] + "\"}";
            crmModel.getEntity().put("address", addr);*/
        }

        //当前就业城市
        if (crmModel.getEntity().get("mapCity") != null && crmModel.getEntity().get("mapCity") != "") {
            if(crmModel.getEntity().get("mapCity") instanceof String){
                String[] address = crmModel.getEntity().get("mapCity").toString().split(",");
                if(address.length == 3){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + address[2] + "\"}";
                    crmModel.getEntity().put("currentCity", addr);
                }else if(address.length == 2){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + "\"}";
                    crmModel.getEntity().put("currentCity", addr);
                }else if(address.length == 1){
                    String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + "\", \"area\":\"" + "\"}";
                    crmModel.getEntity().put("currentCity", addr);
                }else{
                    crmModel.getEntity().put("currentCity",address);
                }
            }else if (crmModel.getEntity().get("mapCity") instanceof LinkedHashMap){
                String province = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapCity")).get("province");
                String city = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapCity")).get("city");
                String area = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapCity")).get("area");
                String addr = "{\"province\":\"" + province + "\", \"city\":\"" + city + "\", \"area\":\"" + area + "\"}";
                crmModel.getEntity().put("currentCity", addr);
            }

            /*String[] address = crmModel.getEntity().get("mapCity").toString().split(",");
            String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + address[2] + "\"}";
            crmModel.getEntity().put("currentCity", addr);*/
        }

        //期望就业城市
//        String addr = "";
//        if (crmModel.getEntity().get("mapWifsuu") != null && crmModel.getEntity().get("mapWifsuu") != "") {
//            if(crmModel.getEntity().get("mapWifsuu") instanceof String){
//                String[] address = crmModel.getEntity().get("mapWifsuu").toString().split(",");
//                if(address.length == 3){
//                     addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + address[2] + "\"}";
//                }else if(address.length == 2){
//                     addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + "\"}";
//                }else if(address.length == 1){
//                     addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + "\", \"area\":\"" + "\"}";
//                }
////                crmModel.getEntity().put("address", addr);
//            }else if (crmModel.getEntity().get("mapWifsuu") instanceof LinkedHashMap){
//                String province = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapWifsuu")).get("province");
//                String city = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapWifsuu")).get("city");
//                String area = (String) ((LinkedHashMap<?, ?>) crmModel.getEntity().get("mapWifsuu")).get("area");
//                addr = "{\"province\":\"" + province + "\", \"city\":\"" + city + "\", \"area\":\"" + area + "\"}";
////                crmModel.getEntity().put("currentCity", addr);
//            }
//
//            /*String[] address = crmModel.getEntity().get("mapWifsuu").toString().split(",");
//            String addr = "{\"province\":\"" + address[0] + "\", \"city\":\"" + address[1] + "\", \"area\":\"" + address[2] + "\"}";
//            crmModel.getField().removeIf(modelField -> "期望就业".equals(modelField.getFieldName()));*/
////            crmModel.getEntity().put("currentCity", addr);
//            /*crmModel.getField().stream().forEach(crmModelFiledVO -> {
//                if("fliedWifsuu".equals(crmModelFiledVO.getFieldName())){
//                    crmModelFiledVO.setValue(addr);
//                }
//            });*/
//            CrmModelFiledVO modelFiledVO = new CrmModelFiledVO();
//            modelFiledVO.setFieldId(1102017);
//            modelFiledVO.setFieldName("fliedWifsuu");
//            modelFiledVO.setValue(addr);
//            crmModel.getField().add(modelFiledVO);
//        }
        crmContactsService.addOrUpdate(crmModel, false);
        return R.ok();
    }

    @PostMapping("/downloadExcel")
    @ApiOperation("下载导入模板")
    public void downloadExcel(HttpServletResponse response) throws IOException {
        crmContactsService.downloadExcel(response);
    }

    @PostMapping("/queryFileList")
    @ApiOperation("查询附件列表")
    public Result<List<FileEntity>> queryFileList(@RequestParam("id") @ApiParam(name = "id", value = "id") Integer id) {
        List<FileEntity> fileEntities = crmContactsService.queryFileList(id);
        return R.ok(fileEntities);
    }

    @PostMapping("/num")
    @ApiOperation("详情页数量展示")
    public Result<CrmInfoNumVO> num(@RequestParam("id") @ApiParam(name = "id", value = "id") Integer id) {
        CrmInfoNumVO infoNumVO = crmContactsService.num(id);
        return R.ok(infoNumVO);
    }

    @PostMapping("/star/{id}")
    @ApiOperation("联系人标星")
    public Result star(@PathVariable("id") @ApiParam(name = "id", value = "id") Integer id) {
        crmContactsService.star(id);
        return R.ok();
    }

    @PostMapping("/querySimpleEntity")
    @ApiExplain("查询简单的联系人对象")
    public Result<List<SimpleCrmEntity>> querySimpleEntity(@RequestBody List<Integer> ids) {
        List<SimpleCrmEntity> crmEntities = crmContactsService.querySimpleEntity(ids);
        return R.ok(crmEntities);
    }

    @PostMapping("/uploadExcel")
    @ApiOperation("导入联系人")
    @SysLogHandler(behavior = BehaviorEnum.EXCEL_IMPORT, object = "导入联系人", detail = "导入联系人")
    public Result<Long> uploadExcel(@RequestParam("file") MultipartFile file, @RequestParam("ownerUserId") Long ownerUserId, @RequestParam("repeatHandling") Integer repeatHandling) {
        UploadExcelBO uploadExcelBO = new UploadExcelBO();
        uploadExcelBO.setOwnerUserId(ownerUserId);
        uploadExcelBO.setUserInfo(UserUtil.getUser());
        uploadExcelBO.setCrmEnum(CrmEnum.CONTACTS);
        uploadExcelBO.setPoolId(null);
        uploadExcelBO.setRepeatHandling(repeatHandling);
        Long messageId = SpringUtils.getBean(CrmUploadExcelService.class).uploadExcel(file, uploadExcelBO);
        return R.ok(messageId);
    }

    @PostMapping("/comparisonExcel/uploadExcel")
    @ApiOperation("智能对照工具表")
    @SysLogHandler(behavior = BehaviorEnum.EXCEL_IMPORT, object = "智能对照工具表", detail = "智能对照工具表")
    public Result<Long> comparisonExcel(@RequestParam("file") MultipartFile file, @RequestParam("ownerUserId") Long ownerUserId,
                                        @RequestParam("vipPeriods") String vipPeriods,
                                        @RequestParam(value = "repeatHandling", required = false) Integer repeatHandling) throws IOException {

        Long messageId = this.crmContactsService.comparisonExcel(file, ownerUserId, repeatHandling, vipPeriods);
        return Result.ok(messageId);
    }

    @PostMapping("/updateInformation")
    @ApiOperation("基本信息保存修改")
    @SysLogHandler(behavior = BehaviorEnum.UPDATE)
    public Result updateInformation(@RequestBody CrmUpdateInformationBO updateInformationBO) {
        crmContactsService.updateInformation(updateInformationBO);
        return R.ok();
    }

    @PostMapping("/dataCheck")
    @ApiOperation("数据查重")
    public Result<List<CrmDataCheckVO>> dataCheck(@RequestBody CrmDataCheckBO dataCheckBO) {
        List<CrmDataCheckVO> crmDataCheckVOS = crmContactsService.dataCheck(dataCheckBO);
        return Result.ok(crmDataCheckVOS);
    }
}

